package com.lingkang.sales.config.exception;

import com.lingkang.sales.common.val.HttpCode;
import com.lingkang.sales.data.dto.ResponseResult;
import java.lang.reflect.UndeclaredThrowableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.javassist.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author linke
 * @date 2020/11/14 22:22
 * @description 自定义异常
 */
@ControllerAdvice
public class CustomException {

  private static final Logger runtimeExceptionLogger = LoggerFactory.getLogger("runtimeException");

  @ExceptionHandler(Exception.class) //也可以只对一个类进行捕获
  public void errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
    System.out.println(e);
    System.out.println(e);
  }

  @ExceptionHandler(NotFoundException.class)
  public String notFoundException(HttpServletRequest request, HttpServletResponse response, Exception e) {
    return "error/404";
  }

  @ExceptionHandler(RuntimeException.class)
  @ResponseBody
  public Object RuntimeException(HttpServletRequest request, HttpServletResponse response, Exception e) {
    System.out.println(e);
    if (e instanceof AccessDeniedException) {
      runtimeExceptionLogger.warn("{} - {}", request.getRequestURL(), e.getMessage());
      return new ResponseResult<>(HttpCode.FAIL, "403，权限不足，无法操作！请联系管理员添加权限。");
    }
    if (e instanceof UndeclaredThrowableException) {
      runtimeExceptionLogger.warn("{} - {}", request.getRequestURL(),
          ((UndeclaredThrowableException) e).getUndeclaredThrowable().getMessage());
      return new ResponseResult<>(HttpCode.FAIL, ((UndeclaredThrowableException) e).getUndeclaredThrowable().getMessage());
    }

    return new ResponseResult<>(HttpCode.FAIL, e.getMessage());
  }

}
